package com.kfh.ybracelet.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.integration.okhttp.OkHttpUrlLoader;
import com.bumptech.glide.load.model.GlideUrl;
import com.kfh.ybracelet.bean.EmoBean;
import com.kfh.ybracelet.mqtt.MQTTService;
import com.kfh.ybracelet.mqtt.MqttManager;
import com.kfh.ybracelet.net.OkHttpStack;
import com.kfh.ybracelet.utils.ParserBrowXml;
import com.squareup.okhttp.OkHttpClient;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

/**
 * application
 * Created by Aaron on 2015/7/27.
 */
public class MyApplication extends Application {

    public static final String TAG = MyApplication.class.getSimpleName();

    public static MyApplication instance = null;
    private Intent serviceIntent;

    public static MyApplication getInstance() {
        return instance;
    }

    // 存放activity
    private List<Activity> activityList = new LinkedList<Activity>();

    private HashMap<String, String> emos;
    private List<EmoBean> emoBeanList;

    /**
     * 我的定位坐标的点
     */
    public double myLatitude;
    public double myLongitude;

    //网络请求队列
    private RequestQueue mRequestQueue;

    public void onCreate() {
        super.onCreate();
        instance = this;

        //初始化图片操作
        Glide.get(this).register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(new OkHttpClient()));

//        // 在Appliction里面设置我们的异常处理器为UncaughtExceptionHandler处理器
//        CrashHandler handler = CrashHandler.getInstance();
//        handler.init(getApplicationContext());

//        // 百度地图在使用SDK各组件之前初始化context信息，传入ApplicationContext
//        // 注意该方法要再setContentView方法之前实现
//        SDKInitializer.initialize(getApplicationContext());

//        sp = getSharedPreferences(Constant.CONFIG, MODE_PRIVATE);

//        LogUtil.e(TAG, "============!~~~~~~~~~~~~~~ " + sHA1(getApplicationContext()) + "~~~~~~~~~~~~~~~~~~~~~~~=======");

        //极光推送
//        JPushInterface.setDebugMode(true);//是否开启debug模式
        JPushInterface.init(this);

//        LogUtil.e("MyApplication", "路由器mac地址:" + getConnectedWifiMacAddress(getApplicationContext()));

    }

//    /**
//     * 获取已连接的Wifi路由器的Mac地址
//     */
//    private String getConnectedWifiMacAddress(Context context) {
//        String connectedWifiMacAddress = null;
//        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//        List<ScanResult> wifiList;
//
//        if (wifiManager != null) {
//            wifiList = wifiManager.getScanResults();
//            WifiInfo info = wifiManager.getConnectionInfo();
//            if (wifiList != null && info != null) {
//                for (int i = 0; i < wifiList.size(); i++) {
//                    ScanResult result = wifiList.get(i);
//                    if (info.getBSSID().equals(result.BSSID)) {
//                        connectedWifiMacAddress = result.BSSID;
//                    }
//                }
//            }
//        }
//        return connectedWifiMacAddress;
//    }


    public RequestQueue getRequestQueue() {

//        String[] hosts = {"kyfw.12306.cn"};
//        int[] certRes = {R.raw.kyfw};
//        String[] certPass = {"asdfqaz"};
//        Hashtable<Object, Object> socketFactoryMap = new Hashtable<>(hosts.length);
//
//        for (int i = 0; i < certRes.length; i++) {
//            int res = certRes[i];
//            String password = certPass[i];
//            SSLSocketFactory sslSocketFactory = createSSLSocketFactory(context, res, password);
//            socketFactoryMap.put(hosts[i], sslSocketFactory);
//        }
//
//        HurlStack stack = new SelfSignSslOkHttpStack(socketFactoryMap);
//
//        requestQueue = Volley.newRequestQueue(getApplicationContext(), stack);
//        requestQueue.start();

        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new OkHttpStack(new OkHttpClient()));
//            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    /**
     * 获取表情的map集合 key是表情的匹配符如[满意], value是图片的名称
     *
     * @return
     */
    public Map<String, String> getEmoMap() {

        if (emos == null || emos.size() == 0) {

            try {
                emos = ParserBrowXml.getInfo(getResources().getAssets().open("brow.xml"));
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        return emos;

    }

    /**
     * 获取表情的list集合
     *
     * @return
     */
    public List<EmoBean> getEmoList() {

        if (emoBeanList == null || emoBeanList.size() == 0) {
            try {
                emoBeanList = ParserBrowXml.getListInfo(getResources().getAssets().open("brow.xml"));
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        return emoBeanList;
    }

    //添加到请求队列
    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        //设置超时时间
        req.setRetryPolicy(new DefaultRetryPolicy(8 * 1000, 1, 1.0f));
        req.setShouldCache(false);
        getRequestQueue().add(req);
    }

    //从请求队列中删除
    public void cancelPendingRequests(Object tag) {
        getRequestQueue().cancelAll(tag);
    }

    // 添加Activity 到容器中
    public void addActivity(Activity activity) {
        activityList.add(activity);
    }

    public void exit() {

        try {

            if (MqttManager.getInstance().getMqttClient() != null && MqttManager.getInstance().getMqttClient().isConnected())
                MqttManager.getInstance().getMqttClient().disconnect();
//            LogUtil.e("tag", "=======退出mqtt=====");

            //关闭聊天服务
            if (serviceIntent != null)
                stopService(serviceIntent);

//            LogUtil.e("tag", " activityList 的集合的个数 : " + activityList.size());

            for (Activity activity : activityList) {

                if (activity != null)
                    activity.finish();

            }
            activityList.clear();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            // 友盟统计
//            MobclickAgent.onKillProcess(this);
            System.exit(0);
        }

    }

    //启动服务, 登录mqtt
    public void loginMqtt() {

        serviceIntent = new Intent(this, MQTTService.class);
        startService(serviceIntent);

    }

    public void exitMqtt() {

        if (serviceIntent != null)
            stopService(serviceIntent);
    }

    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

}
